<template>
    <div class="search-line">
        <el-form v-model="search" inline>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="search.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mopbile">
                <el-input v-model="search.mobile" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item v-show="isExpand" label="角色名" prop="role_name">
                <el-input v-model="search.role_name" placeholder="请输入角色名"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchList">
                    <i class="iconfont icon-sousuo"></i>
                    搜索
                </el-button>
                <el-button @click="searchReset">重置</el-button>
                <span class="switch-btn" @click="isExpand = !isExpand">
                    {{ isExpand ? '收起' : '展开' }}
                    <el-icon v-if="isExpand">
                        <ArrowUp />
                    </el-icon>
                    <el-icon v-else>
                        <ArrowDown />
                    </el-icon>
                </span>
            </el-form-item>
        </el-form>
    </div>
    <div class="user-tab">
        <div class="opBtn">
            <el-button type="danger" size="default" @click="delGroup">
                <i class="iconfont icon-shanchu"></i>
                批量删除
            </el-button>
            <el-button type="primary" size="default" @click="add">
                <i style="font-size: 26px;">+</i>
                添加
            </el-button>
        </div>

        <el-table :data="list" style="width: 100%;" height="460" border ref="multipleTableRef">
            <el-table-column type="selection" align="center">
            </el-table-column>

            <el-table-column align="center" label="编号" prop="user_id" width="120" />
            <el-table-column align="center" prop="role_name" label="所属角色" width="200" />
            <el-table-column align="center" prop="avatar" label="头像" width="120">
                <template #default="scope">
                    <el-avatar shape="circle" :size="40" :src="scope.row.avatar"></el-avatar>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="username" label="用户名" width="200" />
            <el-table-column align="center" prop="mobile" label="手机号" width="200" />
            <el-table-column align="center" prop="state" label="登录" width="200">
                <template #default="scope">
                    {{ scope.row.state }}
                    <el-switch v-model="scope.row.state" class="ml-2" inline-prompt :active-value="1"
                        :inactive-value="0" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        active-text="未冻结" inactive-text="已冻结" @change="switchState($event, scope.row.user_id)" />
                </template>
            </el-table-column>
            <el-table-column align="center" prop="created_at" label="创建于" width="200" />
            <el-table-column align="center" prop="updated_at" label="更新于" width="200" />
            <el-table-column align="center" fixed="right" label="操作" width="240">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="editRow(scope.$index)">
                        <i class="iconfont icon-bianji"></i>
                    </el-button>
                    <el-button type="success" size="small" @click="editRole(scope.$index)">
                        分配角色
                    </el-button>
                    <el-button type="danger" size="small" @click.prevent="deleteRow(scope.$index)">
                        <i class="iconfont icon-shanchu"></i>
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="demo-pagination-block">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 40]" :small="small" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </div>
    <el-dialog v-model="dialogVisible" title="编辑" :width="srceenWidth" :before-close="handleClose">
        <el-form :model="form" label-width="120px" :rules="rules">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" placeholder="请输入密码" />
            </el-form-item>
            <el-form-item label="手机号码">
                <el-input v-model="form.mobile" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="头像">
                <Upload @uploadEvt="getAvatar" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">立即编辑</el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-dialog v-model="dialogVisible1" title="分配角色" :width="srceenWidth" :before-close="handleClose">
        <el-form :model="form1" label-width="120px" :rules="rules">
            <el-form-item label="当前用户" prop="username">
                <el-input :value="form1.username" disabled />
            </el-form-item>
            <el-form-item label="当前角色" prop="role_name">
                <el-input :value="form1.role_name" disabled />
            </el-form-item>
            <el-form-item label="选择角色">
                <el-select v-model="form1.role_name" class="m-2" placeholder="Select" style="width: 240px">
                    <el-option v-for="item in roles" :key="item.role_id" :label="item.role_name"
                        :value="item.role_name" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="upRole">立即更新</el-button>
                <el-button @click="reset1">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>


<script setup>
import { onMounted, ref, reactive } from 'vue'
import { requestIns } from '@/utils/request'
import { useRouter } from 'vue-router'
import { useRolesStore } from '@/stores/roles'
import { storeToRefs } from 'pinia'
import { useConfirm } from '@/hook/useConfirm'

const list = ref([])
const search = ref({
    username: '',
    mobile: '',
    role_name: '',
    created_at: '',
    updated_at: '',
})
const rolesStore = useRolesStore()
const { getRoles } = rolesStore
const { roles } = storeToRefs(rolesStore)
const srceenWidth = ref('50%')
onMounted(() => {
    getList()
    getRoles()
    changeWidth()
})
window.addEventListener('resize', () => {
    changeWidth()
})
const changeWidth = () => {
    if (window.innerWidth < 1000) {
        srceenWidth.value = '90%'
    } else {
        srceenWidth.value = '50%'
    }
}
const dialogVisible = ref(false)
const dialogVisible1 = ref(false)
const router = useRouter()
const isExpand = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const form = reactive({
    username: '',
    password: '',
    mobile: '',
    avatar: ''
})
const form1 = reactive({
    username: '',
    role_name: '',
    role_id: ''
})
const getList = async () => {
    const res = await requestIns.request('/user/index', 'get', {
        pagenum: currentPage.value,
        pagesize: pageSize.value,
        ...search.value
    })
    // console.log(res)
    if (res.state = 200) {
        list.value = res.list
        total.value = res.total
    }

}
const rules = reactive({
    username: [
        { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
    ],
    password: [
        { min: 6, max: 12, message: '长度在 6 到 12 个' }
    ]
})

const handleClose = (done) => {
    done()
}
const deleteRow = async (index) => {

    const item = list.value.find((item, idx) => idx == index)
    // console.log(item.user_id)
    // const res = await requestIns.request('/user/delete', 'delete', {
    //     user_id: item.user_id
    // })
    // console.log(res)
    // if (res.state === 200) {
    //     getList()
    //     ElMessage.success('删除成功')
    // }
    const deleteApi = async (row) => {
        return await requestIns.request('/user/delete', 'delete', {
            user_id: row.user_id
        })
    }

    // 调用useConfirm
    useConfirm(item, deleteApi, getList)
}
const add = () => {
    router.push('/user/create')
}
const multipleTableRef = ref([])
const delGroup = async () => {
    const ids = multipleTableRef.value.getSelectionRows().map(item => item.user_id)
    const res = await requestIns.request('/user/delete', 'delete', {
        user_id: ids.join(',')
    })
    console.log(res)
    if (res.state === 200) {
        getList()
        ElMessage.success('删除成功')
    }

}
const editId = ref(-1)
const editRow = (index) => {
    dialogVisible.value = true
    editId.value = list.value[index].user_id
}
const editRole = (index) => {
    dialogVisible1.value = true
    form1.username = list.value[index].username
    form1.role_name = list.value[index].role_name
    editId.value = list.value[index].user_id
}
const switchState = async (val, id) => {
    const res = await requestIns.request('/user/state', 'put', {
        user_id: id,
        state: val
    })
    console.log(res)


}
const upRole = async () => {
    const id = roles.value.find(item => item.role_name == form1.role_name).role_id
    const res = await requestIns.request('/user/assign', 'put', {
        user_id: editId.value,
        role_id: id
    })
    if (res.state == 200) {
        ElMessage.success(res.msg)
        getList()
        dialogVisible1.value = false
        reset1()
    } else {
        ElMessage.error(res.msg)
    }
}
const getAvatar = (avatar) => {
    form.avatar = avatar
}
const onSubmit = async () => {
    const res = await requestIns.request('/user/update', 'put', {
        user_id: editId.value,
        ...form
    })
    console.log(res)
    if (res.state === 200) {
        ElMessage.success(res.msg)
    } else {
        ElMessage.error(res.msg)
    }
    reset()
    dialogVisible.value = false
    getList()
}
const reset = () => {
    form.username = ''
    form.password = ''
    form.mobile = ''
    form.avatar = ''
}
const reset1 = () => {
    form1.username = ''
    form1.role_name = ''
}
const handleSizeChange = (val) => {
    currentPage.value = 1
    pageSize.value = val
    getList()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getList()
}
const searchList = () => {
    getList()
}
const searchReset = () => {
    search.value.username = ''
    search.value.mobile = ''
    search.value.role_name = ''
    search.value.created_at = ''
    search.value.updated_at = ''
}
</script>

<style lang="scss" scoped>
.user-tab {
    background-color: #fff;
    padding: 15px;

    .opBtn {
        margin-bottom: 15px;
    }
}

.demo-pagination-block {
    margin-top: 10px;
    width: 100%;
    display: flex;
    justify-content: center;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

.search-line {
    background-color: #fff;
    padding: 15px 0 0 15px;
    box-sizing: border-box;
    margin-bottom: 20px;
}

.switch-btn {
    margin-left: 15px;

    &:hover {
        color: #409eff;
        cursor: pointer;
    }
}
</style>